<?php

declare(strict_types=1);
namespace App\Model\PssModel;

use App\Model\BaseModel\BasePssModel;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;
use Service\AppService\IdService;
use App\Service\AppService\SystemCacheConfigService;
use App\Service\AuthService\IdCardVerifyService;

class MerchantAdress extends BasePssModel
{
    public $table = 'merchant_address';
    
    /**
     * 检查收货地址
     */
    public function checkAddress( $param = [] ) 
    {
        //重置分页表名称，需要同一张表join多次的时候
        $this->table = $this->table ." as ma";
        $info = $this
        ->select([
            'ma.id',
            'ma.province as province_id',
            'ma.city as city_id',
            'ma.district as area_id',
            'ap.area_name as provice_name',
            'ac.area_name as city_name',
            'ad.area_name as district_name',
            'ma.receive_address',
            'ma.receive_realname',
            'ma.receive_phone',
            'ma.receive_id_card',
            'ma.buyer_realname',
            'ma.buyer_phone',
            'ma.is_default'
        ])
        ->join('area as ap',"ap.area_id","=","ma.province")
        ->join('area as ac',"ac.area_id","=","ma.city")
        ->join('area as ad',"ad.area_id","=","ma.district")
        ->where([
            'ma.id' => $param['id'],
            'ma.bid' => $param['bid'],
        ])
        ->first();
        if( empty($info) ) {
            return Normal::returnCode(Normal::FAIL,"收获地址不能为空");
        }
        
        $this->table = 'merchant_address';
        return Normal::returnCode(Normal::SUC,"OK",$info->toArray());
    }
    
    /**
     * 收货地址列表
     * @param number $bid
     */
    public function getUserAddressList( $bid = 0 ) 
    {
        //重置分页表名称，需要同一张表join多次的时候
        $this->table = $this->table ." as ma";
        $list = $this
        ->select([
            'ma.id',
            'ma.province as province_id',
            'ma.city as city_id',
            'ma.district as area_id',
            'ap.area_name as provice_name',
            'ac.area_name as city_name',
            'ad.area_name as district_name',
            'ma.receive_address',
            'ma.receive_realname',
            'ma.receive_phone',
            'ma.receive_id_card',
            'ma.buyer_realname',
            'ma.buyer_phone',
            'ma.is_default'
        ])
        ->join('area as ap',"ap.area_id","=","ma.province")
        ->join('area as ac',"ac.area_id","=","ma.city")
        ->join('area as ad',"ad.area_id","=","ma.district")
        ->where([
            'ma.bid' => $bid,
        ])
        ->get()
        ->toArray();
        $this->table = 'merchant_address';
        return Normal::returnCode(Normal::SUC,"获取成功",$list);
    }
    
    /**
     * 添加收货地址
     */
    public function addUserAddress( $param = [] ) 
    {
        $body = $param['body'];
        $binfo = $param['binfo'];
        $res = $this->checkParam($param);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        $res['data']['cd'] = time();
        if( $body['is_default'] == 1 ) {
            $this->edit(['bid'=>$binfo['bid']],['is_default'=>0]);
        }
        
        $res = $this->insert($res['data']);
        if( $res ) {
            return Normal::returnCode(Normal::SUC,"操作成功");
        }
        
        return Normal::returnCode(Normal::FAIL,"操作失败");
    }
    
    /**
     * 删除地址
     * @param array $param
     */
    public function delUserAddress( $param = []) 
    {
        $this->table = 'merchant_address';
        $body = $param['body'];
        $binfo = $param['binfo'];
        if( empty($body['id']) ) {
            return Normal::returnCode(Normal::FAIL,"except param id");
        }
        
        $res = $this->where('id',$body['id'])->where('bid',$binfo['bid'])->delete();
        if( $res ) {
            return Normal::returnCode(Normal::SUC,"操作成功");
        }
        
        return Normal::returnCode(Normal::FAIL,"操作失败");
    }
    
    /**
     * 修改收货地址
     */
    public function editUserAddress( $param = [] )
    {
        $this->table = 'merchant_address';
        $body = $param['body'];
        $binfo = $param['binfo'];
        if( empty($body['id']) ) {
            return Normal::returnCode(Normal::FAIL,"except param id");
        }
        $res = $this->checkParam($param);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        $res['data']['md'] = time();
        
        if( $body['is_default'] == 1 ) {
            $this->edit(['bid'=>$binfo['bid']],['is_default'=>0]);
        }
        
        $res = $this->edit(['id'=>$body['id']],$res['data']);
        if( $res ) {
            return Normal::returnCode(Normal::SUC,"操作成功");
        }
    
        return Normal::returnCode(Normal::FAIL,"操作失败");
    }
    
    public function checkParam( $param )
    {
        $body = $param['body'];
        $binfo = $param['binfo'];
        foreach ($body as & $value ) {
            if( !is_array($value)) {
                $value = checkFields($value);
            }
        }
        
        if( empty($body['receive_address']) ) {
            return Normal::returnCode(Normal::FAIL,"详细收货地址不能为空");
        }
        
        if( empty($body['receive_name']) ) {
            return Normal::returnCode(Normal::FAIL,"收件人不能为空");
        }
        
        if( empty($body['receive_phone']) ) {
            return Normal::returnCode(Normal::FAIL,"收件人手机号码不能为空");
        }
                        
        if( empty($body['province_id']) ) {
            return Normal::returnCode(Normal::FAIL,"请选择省份");
        }
        
        if( empty($body['city_id']) ) {
            return Normal::returnCode(Normal::FAIL,"请选择市");
        }
        
        if( empty($body['area_id']) ) {
            return Normal::returnCode(Normal::FAIL,"请选择区/县");
        }
        
        if( !isset($body['is_default']) ) {
            return Normal::returnCode(Normal::FAIL,"缺少参数is_default");
        }
        
        $province_id        = $body['province_id'];
        $city_id            = $body['city_id'];
        $area_id            = $body['area_id'];
        $receive_address    = $body['receive_address'];
        $receive_name       = $body['receive_name'];
        $receive_phone      = $body['receive_phone'];
        $lists = Area::instance()->getAreaListByIds([$province_id,$city_id,$area_id]);
        if( empty($lists) ) {
            return Normal::returnCode(Normal::FAIL,"省市区信息不存在");
        }
        
        $ids = array_column($lists,null,'area_id');
        if( !isset($ids[$province_id]) || $ids[$province_id]['area_parent_id'] != 0 ) {
            return Normal::returnCode(Normal::FAIL,"省信息不存在");
        }
        
        if( !isset($ids[$city_id]) || $ids[$city_id]['area_parent_id'] != $province_id ) {
            return Normal::returnCode(Normal::FAIL,"省/市信息不存在");
        }
        
        if( !isset($ids[$area_id]) || $ids[$area_id]['area_parent_id'] != $city_id ) {
            return Normal::returnCode(Normal::FAIL,"市/区信息不存在");
        }
        
        if( mb_strlen($receive_address,'utf-8') > 200 ) {
            return Normal::returnCode(Normal::FAIL,"收货地址不能过长");
        }
        
        if( !checkRealName($receive_name) ) {
            return Normal::returnCode(Normal::FAIL,"收货人姓名不正确");
        }
        
        if( !checkPhone($receive_phone) ) {
            return Normal::returnCode(Normal::FAIL,"收货人电话格式不正确");
        }
        
        $arr = [
            'bid'               => $binfo['bid'],
            'receive_realname'  => $receive_name,
            'receive_address'   => $receive_address,
            'receive_phone'     => $receive_phone,
            'province'          => $province_id,
            'city'              => $city_id,
            'district'          => $area_id,
            'is_default'        => $body['is_default'] ??0,
        ];
        
        return Normal::returnCode(Normal::SUC,"校验完成",$arr);
    }
    
    /**
     * @实名认证收货地址
     * @param    array $param
     * @access   public
     * @return   array
     */
    public function idcardauth(array $param = []) 
    {
        if( empty($param['name'])) {
            return Normal::returnCode(Normal::FAIL,"except name");
        }
        
        if( empty($param['idNum'])) {
            return Normal::returnCode(Normal::FAIL,"except idcard");
        }
        return IdCardVerifyService::auth($param);
    }
}